/**
 * Created by MorenYang on 2018/2/1.
 */

const ACTIVE_CLASS = 'layout-steps-item-process',
  FINISHED_CLASS = 'layout-steps-item-finish',
  WAITING_CLASS = 'layout-steps-item-wait';

class Steps {
  constructor(stepSelector, stepForm) {
    this.step = stepSelector;
    this.form = stepForm;
    this.activeIndex = 0;

    this.init();
  }

  init() {
    // 初始化
    if (this.stepLength > 0) {
      $(this.stepItemList)
        .removeClass(ACTIVE_CLASS)
        .removeClass(FINISHED_CLASS)
        .removeClass(WAITING_CLASS);
      $(this.stepItemList[this.activeIndex])
        .toggleClass(ACTIVE_CLASS);
      $(this.stepItemList)
        .not($(this.stepItemList[this.activeIndex]))
        .toggleClass(WAITING_CLASS)
    }
    if (this.formLength > 0) {
      $(this.formItemList)
        .addClass('hidden');
      $(this.formItemList[this.activeIndex])
        .removeClass('hidden')
    }
    if (this.stepLength !== this.formLength) {
      console.debug("Step length error. ")
    }
  }

  next(n) {
    if (!n) n = 1;
    if (this.activeIndex === this.stepLength - 1) return;
    // 把当前的step标志变成finish
    $(this.stepItemList[this.activeIndex])
      .removeClass(ACTIVE_CLASS)
      .toggleClass(FINISHED_CLASS);
    // 把当前form 隐藏
    $(this.formItemList[this.activeIndex])
      .addClass('hidden');
    this.activeIndex++;
    // 激活当前的内容
    $(this.stepItemList[this.activeIndex])
      .removeClass(WAITING_CLASS)
      .toggleClass(ACTIVE_CLASS);
    $(this.formItemList[this.activeIndex])
      .removeClass('hidden');
    if (--n) {
      this.next(n)
    }
  }

  prev(n) {
    if (!n) n = 1;
    if (this.activeIndex === 0) return;
    // 把当前的step标志变成waiting
    $(this.stepItemList[this.activeIndex])
      .removeClass(ACTIVE_CLASS)
      .toggleClass(WAITING_CLASS);
    // 把当前form 隐藏
    $(this.formItemList[this.activeIndex])
      .addClass('hidden');
    this.activeIndex--;
    // 激活当前的内容
    $(this.stepItemList[this.activeIndex])
      .removeClass(FINISHED_CLASS)
      .toggleClass(ACTIVE_CLASS);
    $(this.formItemList[this.activeIndex])
      .removeClass('hidden');
    if (--n) {
      this.prev(n)
    }
  }

  get stepItemList() {
    return this.step.querySelectorAll('.layout-steps-item')
  };

  get stepLength() {
    return this.stepItemList.length
  }

  get formItemList() {
    return this.form.querySelectorAll('.layout-steps-form-item')
  }

  get formLength() {
    return this.formItemList.length
  }
}
